import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;

public class JavaNet {
public static void main(String[] args)throws IOException
{
    int quan=3;
    if(quan==0)
    {
        /*
         * Socket套接字
         * */
        try (var s=new Socket("time-a.nist.gov",13);
             var in=new Scanner(s.getInputStream(), StandardCharsets.UTF_8))
        {
            while(in.hasNextLine())
            {
                String line=in.nextLine();
                System.out.println(line);//打印13端口的信息
            }
        }
    }
    else if(quan==1)
    {
        /*
        * 打印本机ip地址或者打印主机所有ip地址
        * */

        if(args.length>0)
        {
            String host=args[0];
            InetAddress[] addresses=InetAddress.getAllByName(host);
            for(InetAddress a:addresses)
            {
                System.out.println(a);

            }
        }
        else
        {
            InetAddress localHostAddress=InetAddress.getLocalHost();
            System.out.println(localHostAddress);
        }
    }
    else if(quan==2)
    {
        /*
        * 访问8189端口并回复，输入BYE时断开连接
        * */
        try(var s=new ServerSocket(8189))
        {
            try (Socket incoming=s.accept()){
                InputStream inStream=incoming.getInputStream();
                OutputStream outStream=incoming.getOutputStream();
                try(var in=new Scanner(inStream,StandardCharsets.UTF_8))
                {
                    var out =new PrintWriter(new OutputStreamWriter(outStream,StandardCharsets.UTF_8),true);
                    out.println("Hello! Enter BYE to exit.");
                    var done=false;
                    while(!done&&in.hasNextLine())
                    {
                        String line=in.nextLine();
                        out.println("Echo: "+line);
                        if(line.trim().equals("BYE"))
                            done=true;
                    }
                }
            }
        }
    }
    else if(quan==3)
    {
        /**
         * post请求
         */
        String propsFilename=args.length>0?args[0]: "post.properties";
        var props=new Properties();
        try(InputStream in= Files.newInputStream(Paths.get(propsFilename)))
        {
            props.load(in);
        }
        String urlString=props.remove("url").toString();
        Object userAgent=props.remove("User-Agent");
        Object redirects=props.remove("redirects");
        CookieHandler.setDefault(new CookieManager(null,CookiePolicy.ACCEPT_ALL));
        String result=doPost(new URL(urlString),props,userAgent==null?null:userAgent.toString(),redirects==null?-1:Integer.parseInt(redirects.toString()));
        System.out.println(result);
    }

}
public static String doPost(URL url, Map<Object,Object> nameValuePairs,String userAgent,int redirects) throws IOException
{
    var connection=(HttpURLConnection) url.openConnection();
    if(userAgent!=null) connection.setRequestProperty("User-Agent",userAgent);
    if(redirects>=0) connection.setInstanceFollowRedirects(false);
    connection.setDoOutput(true);
    try(var out=new PrintWriter(connection.getOutputStream()))
    {
        var first=true;
        for(Map.Entry<Object,Object> pair: nameValuePairs.entrySet())
        {
            if(first) first=false;
            else out.print('&');
            String name=pair.getKey().toString();
            String value=pair.getValue().toString();
            out.print(name);
            out.print("=");
            out.print(URLEncoder.encode(value,StandardCharsets.UTF_8));
        }
    }
    String encoding=connection.getContentEncoding();
    if(encoding==null) encoding="UTF-8";
    if(redirects>0)
    {
        int responseCode=connection.getResponseCode();
        if(responseCode==HttpURLConnection.HTTP_MOVED_PERM||responseCode==HttpURLConnection.HTTP_MOVED_TEMP||responseCode==HttpURLConnection.HTTP_SEE_OTHER)
        {
            String location=connection.getHeaderField("Location");
            if(location!=null)
            {
                URL base =connection.getURL();
                connection.disconnect();
                return doPost(new URL(base,location),nameValuePairs,userAgent,redirects-1);
            }
        }
    }
    else if(redirects==0)
    {
        throw new IOException("Too many redirects");
    }
    var response=new StringBuilder();
    try(var in=new Scanner(connection.getInputStream(),encoding))
    {
        while(in.hasNextLine())
        {
            response.append(in.nextLine());
            response.append("\n");
        }
    }
    catch (IOException e)
    {
        InputStream err=connection.getErrorStream();
        if(err==null) throw e;
        try(var in=new Scanner(err)) {
            response.append(in.nextLine());
            response.append("\n");
        }
    }
    return response.toString();
}
}
